package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"hc_server/pkg/setting"
	"time"
)

var db *gorm.DB

type Model struct {
	ID        uint `json:"id" form:"id" gorm:"primary_key;AUTO_INCREMENT;comment:'id'"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt *gorm.DeletedAt `sql:"index"`
}

// Setup initializes the database instance
func Setup() {
	var err error
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s&parseTime=true",
		setting.GetConfig().Database.User,
		setting.GetConfig().Database.Password,
		setting.GetConfig().Database.Host,
		setting.GetConfig().Database.Name,
		"10s")
	//连接MYSQL, 获得DB类型实例，用于后面的数据库读写操作。
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})

	if err != nil {
		panic("连接数据库失败, error=" + err.Error())
	}

	sqlDB, _ := db.DB()

	//设置数据库连接池参数
	sqlDB.SetMaxOpenConns(100) //设置数据库连接池最大连接数
	sqlDB.SetMaxIdleConns(20)  //连接池最大允许的空闲连接数，如果没有sql任务需要执行的连接数大于20，超过的连接会被连接池关闭。

	autoMigrate()
}

func autoMigrate() {
	db.AutoMigrate(
		&Agent{},
		&AgentRelation{},
		&Code{},
		&Merchant{},
		&MerchantRange{},
		&MerchantTemp{},
		&MerchantShopType{},
		&MerchantType{},
		&MerchantRelation{},
		&MerchantRate{},
		&MerchantSettlementRate{},
		&Salesmen{},
		&Device{},
		&DeviceModel{},
		&DeviceType{},
		&Activity{},
		&ActivityPolicyTemplate{},
		&AgentRate{},
		&AgentSettlementRate{},
		&SpecialIndustryActivity{},
		&LianMcc{},
		&LianCode{},
		&LianBankCode{},
		&LianMerchantUpload{},
		&LianMerchantRate{},
		&LianMerchantAuthInfo{},
		&MerchantOrder{},
		&MerchantOrderDynamicStatistics{},
		&AgentIncomeLog{},
		&AgentSettlementBank{},
		&AgentWithdrawalLog{},
		&AgentApplyWithdrawalCache{},
	)
}

func Begin() *gorm.DB {
	return db.Begin()
}

func Commit() *gorm.DB {
	return db.Commit()
}

func Rollback() *gorm.DB {
	return db.Rollback()
}
